package com.asyf.gateway.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 参考博客：https://blog.csdn.net/fly910905/article/details/121682625
 */
@Slf4j
@Component
public class MyFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        RequestPath path = request.getPath();
        log.info("path:{}", path);
        //修改ServerHttpRequest实例 修改后不用创建新的exchange
        ServerHttpRequest newServerHttpRequest = request.mutate().header("appid", "appid" + System.currentTimeMillis()).build();
        //构建新的ServerWebExchange实例
        //ServerWebExchange newServerWebExchange = exchange.mutate().request(newServerHttpRequest).build();
        //return chain.filter(newServerWebExchange);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -10;
    }
}
